import { Loading } from 'element-ui';
import config from 'js/config';
import popup from 'lib/popup/popup'
class util {
    constructor() {
        // userAgent
        this.win = window.top;
        this.UA = navigator.userAgent;
        this.isPC = this.UA.indexOf('Windows NT') > -1;
        this.isAndroid = this.UA.indexOf('Android') > -1;
        this.isIos = this.UA.indexOf('Mac OS X') > -1;
        this.isIphone = this.UA.indexOf('iPhone;') > -1;
        this.isIpad = this.UA.indexOf('iPad;') > -1;
        this.isIE7 = this.UA.indexOf('MSIE 7.0;') > -1;
        this.isIE8 = this.UA.indexOf('MSIE 8.0;') > -1;
        this.isIE9 = this.UA.indexOf('MSIE 9.0;') > -1;
        this.isIE10 = this.UA.indexOf('MSIE 10.0;') > -1;
        this.isIE11 = this.UA.indexOf('Trident') > -1;
        // loading
        this.loading = null;
        this.loadingcount = 0;
        this.isLogining = false;
    }
    /*封装的ajax函数
	*type           	类型  get|post
	*url            	api地址
    *data           	请求的json数据
    *async              异步/同步
	*timeout			是否有请求超时
	*complete       	ajax完成后执行（失败成功后都会执行）
	*beforeSend        	请求发送前执行
	*success        	成功之后执行
	*error          	失败之后执行
	*goingError     	是否执行自定义error回调
	*timeout        	ajax超时时间
	*isGoingLogin   	是否跳转到登录界面
	*isShowLoading  	ajax执行是否显示遮罩
    */
    ajax(json) {
        if (!json.url) {
            console.warn('please inner your url');
            return;
        }
        if (json.async && typeof (json.async) !== 'boolean') {
            console.warn('async must be boolean');
            return;
        }
        if (json.timeout && typeof (json.timeout) !== 'number') {
            console.warn('timeout must be number');
            return;
        }
        let This = this,
            timer = null,
            noerror = true;
        let option = {
            isShowLoading: json.isShowLoading || true,
            header:json.header||{},
        }
        if (option.isShowLoading) {
            this.showLoading();
        }
        let conf = {
            type: json.type || 'post',
            url: json.url,
            data: json.data || {},
            async: json.async || true,
            timeout: json.timeout || config.ajaxtimeout,
            beforeSend(xhr) {
                for(let n in option.header){
                    xhr.setRequestHeader(n, option.header[n]);
                }
                let userinfo = This.getStorage('local', 'userinfo');
                if (userinfo && JSON.parse(userinfo).openid){
                    xhr.setRequestHeader('openId', JSON.parse(userinfo).openid);
                }
                json.beforeSend && json.beforeSend(xhr)
            },
            success(data) {
                if (typeof (data) == 'string') {
                    This.success(JSON.parse(data), json);
                } else {
                    This.success(data, json);
                }
            },
            error(xhr) {
                noerror && This.error(xhr, json)
            },
            complete(xhr) {
                --This.loadingcout;
                timer && clearTimeout(timer);
                if (This.loadingcount === 0) {
                    This.hideLoading();
                }
            }
        }
        if (conf.timeout !== 0) {
            timer = setTimeout(() => {
                if (option.isShowLoading) {
                    this.hideLoading();
                }
                noerror = false;
                conf.async && popup.alert({ content: '您的网络太慢了哦,请刷新重试!' })
            }, conf.timeout);
        }
        ++this.loadingcout;//执行计数
        return $.ajax(conf)
    };
    success(data, json) {
        let code = data.code - 0;
        if (!json.isGoingLogin && code == 1003) {
            location.href="/login/login"
            // if (!this.isLogining){
            //     this.isLogining = true;
            //     server.getUserInfo(true).then(() => {
            //         this.isLogining = false;
            //     });
            // }
            // popup.alert({
            //     content: '用户未登陆,请登录!',
            //     yes: () => {
            //         location.href = config.loginUrl
            //     }
            // });
        } else {
            switch (code) {
                case 1000:
                    json.success && json.success(data);
                    break;
                default:
                    if (json.goingError) {
                        //走error回调
                        json.error && json.error(data);
                    } else {
                        //直接弹出错误信息
                        popup.alert({ content: data.desc });
                    };
            }
        };
    };
    error(XMLHttpRequest, json) {
        if (json.code) {
            json.error(JSON.parse(XMLHttpRequest.responseText));
        } else {
            switch (XMLHttpRequest.status) {
                case 401:
                    popup.alert({ content: XMLHttpRequest.status })
                    break;
                case 400:
                    popup.alert({ content: XMLHttpRequest.status })
                    break;
                case 404:
                    popup.alert({ content: XMLHttpRequest.status })
                    break;
                case 500: case 502:
                    popup.alert({ content: XMLHttpRequest.status })
                    break;
            }
        }
    };


    // loading
    showLoading() {
        this.loading = Loading.service({
            fullscreen: true
        });
    };
    hideLoading() {
        this.loading && this.loading.close();
    };

    /*根据参数生成常用的正则表达式
    *string    type 生成的正则表达式类型
    *array     numArr 生成正则的条件数组 例如:[6,16] 也可省略
    */
    regCombination(type, numArr) {
        var reg = "";
        switch (type) {
            case "*":     //"*":"不能为空！"   
                if (numArr) {
                    reg = new RegExp("^[\\w\\W]{" + numArr[0] + "," + numArr[1] + "}$");
                } else {
                    reg = new RegExp("^[\\w\\W]+$");
                }
                break;
            case "n":    //"number":"请填写数字！
                if (numArr) {
                    reg = new RegExp("^\\d{" + numArr[0] + "," + numArr[1] + "}$");
                } else {
                    reg = new RegExp("^\\d+$");
                }
                break;
            case "s":  //"s":"不能输入特殊字符！"   
                if (numArr) {
                    reg = new RegExp("^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\w\\.\\s]{" + numArr[0] + "," + numArr[1] + "}$");
                } else {
                    reg = new RegExp("^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\w\\.\\s]+$");
                }
                break;
            case "c":  //"z":"中文验证" 
                reg = new RegExp("^[\\u4E00-\\u9FA5\\uf900-\\ufa2d]{" + numArr[0] + "," + numArr[1] + "}$");
                break;
            case "p":    //"p":"邮政编码！
                reg = new RegExp("^[0-9]{6}$");
                break;
            case "m":    //"m":"写手机号码！"
                reg = new RegExp("^13[0-9]{9}$|14[0-9]{9}$|15[0-9]{9}$|17[0-9]{9}$|18[0-9]{9}$");
                break;
            case "e":   //"e":"邮箱地址格式
                reg = new RegExp("^\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
                break;
            case "id":   //"id":验证身份证
                reg = new RegExp("^\\d{17}[\\dXx]|\\d{14}[\\dXx]$");
                break;
            case "money": //钱
                reg = new RegExp("^[\\d\\.]+$");
                break;
            case "url":   //"url":"网址"
                reg = new RegExp("^(\\w+:\\/\\/)?\\w+(\\.\\w+)+.*$");
                break;
            case "u":    //
                reg = new RegExp("^[A-Z\\d]+$");
                break;
        }
        return reg;
    }

    //设置cookie
    setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + ";path=/; " + expires;
    }
    //获取cookie
    getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1);
            if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
        }
        return "";
    }
    //清除cookie  
    clearCookie(name) {
        this.setCookie(name, "", -1);
    }

    /*获取 storage 缓存数据
	* type  类型   local：localStorage   session：sessionStorage
	* name  缓存数据name名
	*/
    getStorage(type, name) {
        var type = type || 'local';
        if (type == 'local') {
            var result = localStorage.getItem(name) ? localStorage.getItem(name) : "";
        } else if (type == 'session') {
            var result = sessionStorage.getItem(name) ? sessionStorage.getItem(name) : "";
        }
        return result;
    }

    /*设置 storage 缓存数据
    *type  类型   local：localStorage   session：sessionStorage
    *name  缓存数据name名
    *content  缓存的数据内容
    */
    setStorage(type, name, content) {
        var type = type || 'local';
        var data = content;
        if (typeof (data) == 'object') { data = JSON.stringify(content) };
        if (type == 'local') {
            localStorage.setItem(name, data);
        } else if (type == 'session') {
            sessionStorage.setItem(name, data);
        }
    }

    //秒数换算成时间函数 得到00:00:00 格式
    formatSeconds(value) {
        var second = parseInt(value);// 秒
        var minute = 0;// 分
        var hour = 0;// 小时
        if (second > 60) {
            minute = parseInt(second / 60);
            second = parseInt(second % 60);
            if (minute > 60) {
                hour = parseInt(minute / 60);
                minute = parseInt(minute % 60);
            }
        }
        var result = this.getZero(minute) + ':' + this.getZero(parseInt(second));
        if (minute > 0) {
            result = this.getZero(parseInt(minute)) + ":" + this.getZero(parseInt(second));
        }
        if (hour > 0) {
            result = this.getZero(parseInt(hour)) + ':' + this.getZero(parseInt(minute)) + ":" + this.getZero(parseInt(second));
        }
        return result;
    }
    /*判断时间前面是否加0*/
    getZero(num) {
        if (num < 10) {
            return '0' + num;
        } else {
            return num;
        }
    }

    /* 短信定时器
      nowTime vue.js 初始数据  当前时间
      getMsgText vue.js 初始数据  当前的提示文字
    */
    getMsgTime(This, msgText) {
        var nowTime = config.msgTime;
        return new Promise((resolve, reject) => {
            var timer = setInterval(() => {
                console.log(nowTime)
                nowTime--;
                This[msgText] = nowTime + ' S后重发';
                //时间走完时执行
                if (nowTime <= 0) {
                    clearInterval(timer);
                    This[msgText] = "重新获取";
                    resolve();
                }
            }, 1000);
        })
    }

    //新建iframe 并赋src   文件下载时用得到
    interIosForIframe(filename, src, isEncode) {
        var a = document.createElement('a');
        a.href = src;
        a.download = filename;
        document.body.append(a);
        a.click();
        a.remove();
    };

    /*---------数据操作start-------------*/
    /*传入一个对象，返回该对象的值不为空的所有参数，并返回一个对象
     obj   object    传入的对象
    */
    objDislodge(obj, noclone) {
        var objData = noclone ? obj : JSON.parse(JSON.stringify(obj));
        for (var n in objData) {
            if (objData[n] === null || objData[n] === '') {
                delete objData[n]
            }
        }
        return objData;
    }

    /*传入一个json对象，返回该对象的值不为空的所有参数，并返回一个对象
     json   object    传入的对象
    */
    jsonDislodge(json) {
        var objData = JSON.parse(JSON.stringify(obj));
        objData.forEach((item, index) => {
            for (let n in item) {
                if (item[n] == null || item[n] == '') {
                    delete item[n]
                }
            }
        })
        return objData;
    }

    /*将json里面某个参数的参数名替换成另外一个参数名
     name1:初始参数名
     name2:替换后参数名
    */
    jsonNameReplace(json, name1, name2) {
        var json = JSON.parse(JSON.stringify(json));
        json.forEach((item, index) => {
            item[name2] = item[name1];
            delete item[name1];
        })
        return json;
    }

    /*
     除掉对象里面的某些参数
    */
    delObjByArr(obj, arr) {
        var obj = obj;
        arr.forEach((item, index) => {
            delete obj[item]
        })
        return obj;
    }

    /*
     传入一个json数组和所需要的参数集，返回一个全新的json数组
    */
    getNewJson(json, arr) {
        var array = [];
        json.forEach((item, index) => {
            var obj = {};
            for (var i = 0, len = arr.length; i < len; i++) {
                for (var n in item) {
                    if (arr[i] == n) {
                        obj[arr[i]] = item[n];
                    }
                }
            }
            array.push(obj);
        })
        return array;
    }

    /*
     传入一个对象和所需要的参数集，返回一个全新的对象
    */
    getNewObj(obj, arr) {
        var object = {};
        for (var n in obj) {
            for (var i = 0, len = arr.length; i < len; i++) {
                if (n == arr[i]) {
                    object[n] = obj[n]
                }
            }
        }
        return object;
    }
    /*---------数据操作end-------------*/
    /*获取url hash*/
    getQueryString(name, hash) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        if (hash) {
            if (!window.location.hash) {
                return '';
            };
            var r = decodeURIComponent(window.location.hash).substr(1).match(reg);
        } else {
            var r = decodeURIComponent(window.location.search).substr(1).match(reg);
        }
        if (r != null) {
            return r[2];
        }
        return null;
    }
}
window['util'] = new util();